<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Address;
use Illuminate\Http\Request;
use App\Models\Authorization;
use App\Transformers\AddressTransformer;
use Illuminate\Support\Facades\DB;
use Log;

class AddressController extends BaseController
{
    /**
     *
     * 获取用户的地址列表
     * @param {Object} Request
     */
    public function index(Request $request)
    {
        
		$addrs = Address::where(['user_id' => $this->user()->id])
		    ->paginate();
		
		$addrs = $this->response->paginator($addrs, new AddressTransformer());
		// $products = Product::whereIn('user_id', $userId)->get();
		return $this->returnSuccess($addrs);
    }
    
    /*
     * 获取商品的详细信息
     */
    public function detail(Request $request)
    {
        $id = $request->get('id');
        $user_id = $request->get('user_id');
        $data = [];
        return $this->returnSuccess($data);
    }
    
    /*
     * 添加/编辑地址
     */
    public function add(Request $request)
    {
        $validator = \Validator::make($request->input(), [
            'describe' => 'required|string|max:255',
            'address' => 'required|string|max:255',
            'name' => 'required|string|max:255',
        ]);
        
        if ($validator->fails()) {
            return $this->returnError($validator);
        }
        
        $attributes = $request->only('is_default', 'name', 'address','describe', 'longitude', 'latitude');
        $attributes['user_id'] = $this->user()->id;
		$id = $request->get('id');
		\Log::info('id '.$id);
		if($id){
			$address = Address::findOrFail($id);
			$data = $address->update($attributes);
		}else{
			$data = Address::insertGetId($attributes);
			$id = $data;
		}
		if(isset($attributes['is_default']) && $attributes['is_default']){
			$affected = Address::where('id', '!=', $id)->update(['is_default' => 0]);
		}
        return $this->returnSuccess($data);
    }
}
